package com.example.springcaptcha;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;

@RestController
@RequestMapping("/Captcha")
public class HuToolCaptchaController {
    private final static long session_captcha_timeout=60*1000;
    @Autowired
    private Constants constants;
    @RequestMapping("/getCaptcha")
    public void getCaptcha(HttpServletResponse response, HttpSession session){
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(200, 100);
        //图形验证码写出，可以写出到文件，也可以写出到流
        try {

            lineCaptcha.write(response.getOutputStream());
            System.out.println(lineCaptcha.getCode());
            session.setAttribute(constants.getKey(),lineCaptcha.getCode());
            session.setAttribute(constants.getDate(),System.currentTimeMillis());
            response.getOutputStream().close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    @RequestMapping("/check")
    public boolean check(String inputCode,HttpSession session){
        if(!StringUtils.hasLength(inputCode)){
            return false;
        }
        String savedCode=(String) session.getAttribute(constants.getKey());
        long savedTime=(Long) session.getAttribute(constants.getDate());
        if (inputCode.equalsIgnoreCase(savedCode)){
            if(savedCode!=null && System.currentTimeMillis()-savedTime < session_captcha_timeout){
                return true;
            }
        }
        return false;
    }
}
